'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
const serviceName = 'address'
class RouterController extends Controller {
  // 分页
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize, name = '', member_id } = query;
    let page = Number(pageNum) || 1;
    let size = Number(pageSize) || 10;
    const where = {
      member_id
    };
    const list = await service[serviceName].getPage(where, page, size);
    this.ctx.success(list);
  }
  // 新增
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service[serviceName].create(data);
    ctx.success(data, 200);
  }
  // 修改
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[serviceName].update(id, infos);
    ctx.success(id, 200);
  }
  async updateStatus() {
    // 更新默认状态，数据库只能存在一条默认地址
    const { ctx } = this;
    const { id, member_id } = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    // 查找当前用户的所有地址
    const list = await ctx.service[serviceName].allList({ member_id });
    // 更新当前地址为默认地址，其他地址为非默认地址
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        let is_default = 0
        if (item.id === id) {
          is_default = 1;
        } else {
          is_default = 0;
        }
        await ctx.service[serviceName].update(item.id, {
          ...item,
          is_default
        });
    }
    ctx.success(id, 200);
  }
  // 删除
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[serviceName].deleteById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }
  // 查看
  async show() {
    const { params, service } = this.ctx;
    const findItem = await service[serviceName].findOne(params.id);
    this.ctx.success(findItem);
  }
  // 所有列表
  async allList() {
    const { query, service } = this.ctx;
    let { member_id } = query;
    const where = {
      member_id
    }
    const list = await service[serviceName].allList(where);
    this.ctx.success(list);
  }
}

module.exports = RouterController;
